<template>
  <div class="state-transition-manager">
    <div class="transition-header">
      <h4>状态转换规则</h4>
      <a-button
        type="primary"
        size="small"
        @click="handleCreateTransition"
      >
        <template #icon>
          <Icon name="plus" />
        </template>
        新建转换
      </a-button>
    </div>

    <div class="transition-content">
      <a-spin :spinning="loading">
        <div v-if="transitions.length > 0" class="transition-list">
          <div
            v-for="transition in transitions"
            :key="transition.id"
            class="transition-item"
            :class="{ 'transition-item-inactive': !transition.is_active }"
          >
            <div class="transition-flow">
              <div class="from-state">
                <StateTag :state="getStateById(transition.from_state_id)" variant="outlined" />
              </div>
              <div class="transition-arrow">
                <Icon name="arrow-right" />
              </div>
              <div class="to-state">
                <StateTag :state="getStateById(transition.to_state_id)" variant="outlined" />
              </div>
            </div>
            
            <div class="transition-info">
              <div class="transition-name">{{ transition.name }}</div>
              <div v-if="transition.description" class="transition-description">
                {{ transition.description }}
              </div>
              <div class="transition-meta">
                <a-tag v-if="!transition.is_active" color="red" size="small">禁用</a-tag>
                <span v-if="transition.permissions?.length" class="permissions">
                  权限: {{ transition.permissions.join(', ') }}
                </span>
              </div>
            </div>

            <div class="transition-actions">
              <a-button
                type="text"
                size="small"
                @click="handleEditTransition(transition)"
              >
                <template #icon>
                  <Icon name="edit" />
                </template>
              </a-button>
              <a-button
                type="text"
                size="small"
                danger
                @click="handleDeleteTransition(transition)"
              >
                <template #icon>
                  <Icon name="delete" />
                </template>
              </a-button>
            </div>
          </div>
        </div>
        <a-empty v-else description="暂无转换规则" />
      </a-spin>
    </div>

    <!-- 转换编辑对话框 -->
    <StateTransitionEditDialog
      v-model:open="editDialogVisible"
      :transition="editingTransition"
      :states="states"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { StateResponse } from '@/types/state'
import type { StateTransition } from '@/api/state'
import { stateTransitionApi } from '@/api/state'
import StateTag from './StateTag.vue'
import StateTransitionEditDialog from './StateTransitionEditDialog.vue'
import Icon from '@/components/ui/Icon.vue'

interface Props {
  moduleType: string
  states: StateResponse[]
}

const props = defineProps<Props>()

const loading = ref(false)
const transitions = ref<StateTransition[]>([])
const editDialogVisible = ref(false)
const editingTransition = ref<StateTransition | null>(null)

// 根据ID获取状态
const getStateById = (stateId: string) => {
  return props.states.find(state => state.id === stateId) || {
    id: stateId,
    name: '未知状态',
    code: 'UNKNOWN',
    color: '#8c8c8c',
    module_type: props.moduleType,
    is_enabled: false,
    is_visible: false,
    is_default: false,
    sort_order: 999,
    created_at: '',
    updated_at: ''
  }
}

// 加载转换规则
const loadTransitions = async () => {
  if (!props.moduleType || !props.states.length) return
  
  loading.value = true
  try {
    const stateIds = props.states.map(state => state.id)
    const response = await stateTransitionApi.getTransitions({
      module_type: props.moduleType
    })
    
    // 处理API响应格式
    let transitionsData: StateTransition[] = []
    if (response?.data) {
      // 如果是统一响应格式
      if (Array.isArray(response.data)) {
        transitionsData = response.data
      } else if (response.data.data && Array.isArray(response.data.data)) {
        transitionsData = response.data.data
      }
    } else if (Array.isArray(response)) {
      transitionsData = response
    }
    
    // 过滤出当前模块的转换规则
    transitions.value = transitionsData.filter(transition =>
      stateIds.includes(transition.from_state_id) || stateIds.includes(transition.to_state_id)
    )
  } catch (error) {
    console.error('加载转换规则失败:', error)
    message.error('加载转换规则失败')
    transitions.value = []
  } finally {
    loading.value = false
  }
}

// 处理创建转换
const handleCreateTransition = () => {
  if (props.states.length < 2) {
    message.warning('至少需要2个状态才能创建转换规则')
    return
  }
  editingTransition.value = null
  editDialogVisible.value = true
}

// 处理编辑转换
const handleEditTransition = (transition: StateTransition) => {
  editingTransition.value = transition
  editDialogVisible.value = true
}

// 处理删除转换
const handleDeleteTransition = (transition: StateTransition) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除转换规则"${transition.name}"吗？此操作不可恢复。`,
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk: async () => {
      try {
        await stateTransitionApi.deleteTransition(transition.id)
        message.success('删除成功')
        loadTransitions()
      } catch (error) {
        console.error('删除转换规则失败:', error)
        message.error('删除转换规则失败')
      }
    }
  })
}

// 处理编辑成功
const handleEditSuccess = () => {
  editDialogVisible.value = false
  loadTransitions()
}

// 监听状态变化
watch(
  () => [props.moduleType, props.states],
  () => {
    loadTransitions()
  },
  { deep: true }
)

onMounted(() => {
  loadTransitions()
})
</script>

<style scoped>
.state-transition-manager {
  margin-top: 32px;
}

.transition-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.transition-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #262626;
}

.transition-list {
  display: grid;
  gap: 12px;
}

.transition-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.transition-item:hover {
  border-color: #d9d9d9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.transition-item-inactive {
  opacity: 0.6;
  background: #fafafa;
}

.transition-flow {
  display: flex;
  align-items: center;
  gap: 12px;
}

.transition-arrow {
  color: #8c8c8c;
  font-size: 16px;
}

.transition-info {
  flex: 1;
  margin-left: 24px;
}

.transition-name {
  font-weight: 500;
  color: #262626;
  margin-bottom: 4px;
}

.transition-description {
  font-size: 12px;
  color: #595959;
  margin-bottom: 8px;
}

.transition-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.permissions {
  font-size: 12px;
  color: #8c8c8c;
}

.transition-actions {
  display: flex;
  gap: 4px;
}
</style>